package utils

import (
	"errors"
	"strconv"
	"strings"
)

type Integer interface {
	~int | ~int8 | ~int16 | ~int64 | ~int32 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

// IntSliceToString 整数数组转字符串
func IntSliceToString[T Integer](input []T) (string, error) {
	slc := []string{}
	for _, num := range input {
		var s string
		switch any(num).(type) {
		case int64, int32, int16, int8, int:
			s = strconv.FormatInt(int64(num), 10)
		case uint64, uint32, uint16, uint8, uint:
			s = strconv.FormatUint(uint64(num), 10)
		default:
			return "", errors.New("Type error")
		}
		slc = append(slc, s)
	}
	return strings.Join(slc, ","), nil
}

// StringToIntSlice 字符串转整数数组
func StringToIntSlice[T Integer](input string) ([]T, error) {
	if input == "" {
		return []T{}, nil
	}
	parts := strings.Split(input, ",")
	var result []T
	for _, part := range parts {
		trimmed := strings.TrimSpace(part)
		if trimmed == "" {
			continue
		}
		// 统一用 int64 解析，再转换为目标类型
		parsed, err := strconv.ParseInt(trimmed, 10, 64)
		if err != nil {
			return nil, errors.New("Format error")
		}
		result = append(result, T(parsed)) // 强制类型转换
	}
	return result, nil
}
